package com.bai.ruiji.Controller;

import com.bai.ruiji.Common.R;
import com.bai.ruiji.Service.EmployeeService;

import com.bai.ruiji.pojo.Employee;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author 27471
 * Time : 2022/10/6 11:29
 */
@Slf4j
@RestController//@Controller+@ResponseBody 将此类标志为Controller类并且此类的返回值为JSON数据
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @return
     * @RequestBody 用来接受前端传给后端的JSON数据(请求体中的)，最多只能有一个
     * 可以和@RequestParam()一起使用，但@RequestParan()可以有多个
     * HttpServletRequest 将查询到的用户id添加到session域中，表示登录成功
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //将前端获取的密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据用户名查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //eq 等于
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
        //若果没有查到返回 msg:用户不存在
        if (emp == null) {
            return R.error("用户不存在");
        }
        //判断密码是否正确
        if (!emp.getPassword().equals(password)) {
            return R.error("密码错误");
        }
        //判断账号是否被禁用
        if (emp.getStatus() == 0) {
            return R.error("账号已被禁用");
        }
        //登录成功则把用户id存入session
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清理session中保存的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工，员工信息：{}", employee.toString());
        //设置初始密码123456,需要进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //获得当前登录用户id
        Long empId = (Long) request.getSession().getAttribute("employee");

        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);

        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @RequestMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page={},pageSize={},name={}",page,pageSize,name);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //添加一个过滤条件
        /**
         * StringUtils.isNotEmpty(name)若果name不为空则添加，为空则不添加
         * Employee::getName,name将name封装到Employee中
         */
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据id修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());
        Long employee1 =(Long) request.getSession().getAttribute("employee");
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(employee1);
        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }

    /**
     *根据id查询用户信息(回显给浏览器)
     * @PathVariable 映射URL绑定的占位符，将URL中的占位符传入控制器处理方法的参数中
     * 一般使用在GET请求中
     * 1、若方法参数名称和需要绑定的url中变量名称一致时,可以省略参数
     * 2、若方法参数名称和需要绑定的url中变量名称不一致时，则写成@PathVariable("xxx")
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if (employee!=null) {
            return R.success(employee);
        }
        return R.error("没有查询到用户信息");
    }
}
